// 用户模块-mysql服务处理

// 引入数据库模块
const db = require('../config/mysql.js')
const utils = require("../common/utils")
const bcrypt = require('bcryptjs')
// 引入jwt
const jwt = require('jsonwebtoken')
const secretKey = 'ethink'    // 密钥

// 获取菜单
const getMenuList = (id) => {
  return new Promise((resolve, reject) => {
    let sql = `select menu_id from role_menu where role_id = "${id}"`
    db.query(sql, (err, result) => {
      if (err) return reject(err)
      // 角色拥有的菜单
      const hasMenu = JSON.parse(result[0].menu_id)
      // 所有的菜单（未被禁用的）
      db.query(`select * from menu where status = 1`, (err1, result1) => {
        if (err1) return reject(err1)
        const newArr = []
        hasMenu.forEach(item => {
          let index = result1.findIndex(el => el.id == item)
          if (index != -1) {
            newArr.push(result1[index])
          }
        })
        // 最终菜单列表
        const menuList = utils.organizeMenuData(newArr)
        return resolve(menuList)
      })
    })
  })
}

// 修改密码
const updatePassword = (data) => {
  return new Promise((resolve, reject) => {
    let { id, email, password, newPassword } = data
    // 判断原密码是否正确
    let sql = `select password from user where id = "${id}" and email = "${email}"`
    db.query(sql, (err, result) => {
      if (err) return reject(err)
      if (result.length != 1) return reject("修改失败，ID和邮箱不匹配")
      // 密码比对
      let compareResult = bcrypt.compareSync(password, result[0].password)
      if (!compareResult) return reject('原密码错误，请重新输入')
      // 原密码匹配成功
      // 旧密码与新密码比对
      if (password == newPassword) return reject('新密码不能与旧密码相同，请重新输入')
      // 修改密码
      let uPassword = bcrypt.hashSync(newPassword, 10)
      let updateSql = `update user set password = "${uPassword}" where id = "${id}" and email = "${email}"`
      db.query(updateSql, (err1, result1) => {
        if (err1) return reject(err1)
        if (result1.affectedRows == 1) return resolve("密码修改成功，请重新登录")
        return reject("密码修改失败")
      })
    })
  })
}

module.exports = {
  getMenuList,
  updatePassword
}